<template>
  <div class="container">

    <IsLoading v-if="isLoading"></IsLoading>

      <!-- 页面内容 -->
      <div class="content">
        <div class="custom-breadcrumb">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/front/homeFront' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: $route.path }">{{ $route.meta.name }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <!--      <div style="font-size: 20px;font-weight: bold;margin: 20px 15px">用户反馈</div>-->

        <el-divider></el-divider>

        <img src="@/assets/imgs/feedBack.png" class="img">

        <div class="feed">
          <span class="back">用户反馈</span>
          <span class="feedBack">知行邦不是完美的，您的反馈将会被认真对待!</span>
        </div>

        <div class="form">

          <el-form :model="form" ref="formRef" :rules="rules" label-width="160px">
            <el-form-item prop="img" label="图片">
              <el-upload
                  name="file"
                  class="avatar-uploader"
                  action="http://zjdownload.xyhelp.cn/prod-api/common/upload"
                  :headers="{ Authorization: `Bearer ${token}` }"
                  :file-list="fileList"
                  list-type="picture"
                  :on-success="handleImgSuccess"
              >
                <!--            <img v-if="form.img" :src="form.img" :style="{ width: '200px', height: '150px' }">-->
                <div class="upload">
                  <el-button type="primary" icon="el-icon-upload">上传图片</el-button>
                  <div class="label">请上传[bmp, gif, jpg, jpeg, png, doc, docx, xls, xlsx, ppt, pptx, html,
                    htm, txt, rar, zip, gz, bz2, mp4, avi, rmvb, pdf]格式的图片
                  </div>
                </div>

              </el-upload>
            </el-form-item>
            <el-form-item label="反馈主题" prop="title">
              <el-input class="input"
                        v-model="form.title"
                        autocomplete="off"
                        placeholder="请输入反馈内容的链接/名称/标题"></el-input>
            </el-form-item>
            <el-form-item prop="description" label="问题描述">
              <el-input class="input" type="textarea" :autosize="{ minRows: 4, maxRows: 6}"
                        v-model="form.description" autocomplete="off"
                        placeholder="请详细描述您反馈的问题，以便我们高效处理"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
              <el-input class="input" v-model="form.email" autocomplete="off"
                        placeholder="请输入您的邮箱，受理后我们将通过邮箱回复您!"></el-input>
            </el-form-item>
            <el-form-item prop="code" label="验证码">
              <div style="display: flex;flex-direction: row">
                <el-input class="input-img" v-model="form.code" autocomplete="off"
                          placeholder="请输入验证码"></el-input>
                <div class="captcha-container">
                  <img :src="base64Image + Image" class="captcha-image" alt="验证码" @click="updataImg">
                </div>
              </div>
            </el-form-item>
          </el-form>

          <el-button style="margin-left: 50%" type="primary" @click="submitForm">确 定</el-button>
        </div>

        <!--    遮罩层-->
        <div class="overlays" v-if="!userInfo"></div>
        <!-- 模态框容器 -->
        <div class="qrcode-login" v-if="showQRCodeModal">
          <div style="display: flex;flex-direction: row">
            <h2 style="font-weight: bold;font-size: 18px;margin-top: 10px">助教下载站</h2>
          </div>

          <div class="qrcode-modal">
            <!-- 关闭按钮 -->
            <el-button type="text" class="close-btn" @click="close" icon="el-icon-close"></el-button>
            <!-- 显示二维码图片 -->
            <img class="qrcode-img" :src="data.QRImageUrl" alt="二维码"/>
          </div>
          <p style="margin: 10px 0;text-align: center">微信扫码，授权登录</p>


          <span style="text-align: center;margin-top: 50px">登录即表示已阅读并同意《
        <el-button @click="toContact()" type="text">用户协议</el-button>》和《
        <el-button @click="toPrivate()" type="text">隐私政策</el-button>》</span>
        </div>
      </div>
  </div>
</template>

<script>
export default {
  name: "FeedBack",

  data() {
    return {
      form: {},
      rules: {
        img: [
          {required: true, message: '请上传图片', trigger: 'blur'},
        ],
        title: [
          {required: true, message: '请输入反馈主题', trigger: 'blur'},
          {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入问题描述', trigger: 'blur'},
        ],
        email: [
          {required: true, message: '请填写邮箱', trigger: 'blur'},
          {
            type: 'string', message: '邮箱格式不正确', trigger: 'blur',
            transform(value) {
              if (!/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(value)) {
                return true
              } else {
              }
            }
          },
          {type: 'string', message: '长度不能超过30位', trigger: 'blur', max: 30}
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {pattern: /^[0-9]\d*$/, message: '只能输入整数',}
        ],
      },
      Image: '',
      base64Image: 'data:image/gif;base64,',
      uuid: '',
      scale: 1,  // 初始缩放比例为 1，即原始大小
      userInfo: JSON.parse(localStorage.getItem('userInfo')),
      fileList: [],
      token: localStorage.getItem('token') || {},
      showQRCodeModal: false, // 控制模态框的显示
      refreshInterval: null, // 刷新二维码的定时器
      checkStatusInterval: null, // 检查扫码状态的定时器
      data: '',
      isLoading: true
    }
  },
  // created() {
  //   this.loadLogin()
  //   this.loadcaptchaImage()
  // },
  beforeRouteEnter(to, from, next) {
    // 判断是否从特定页面跳转过来
    if (from.name === 'Search') {
      next(vm => {
        // 在组件实例创建后刷新页面
        window.location.reload();
      });
    } else {
      next();
    }
  },
  created() {
    this.loadLogin();
    Promise.all([
      this.loadcaptchaImage()
    ]).then(() => {
      this.isLoading = false;
    }).catch((error) => {
      console.error('Error loading data:', error);
      this.isLoading = false;
    });
  },
  mounted() {
    // 监听滚轮事件
    window.addEventListener('wheel', this.handleWheelEvent);
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('wheel', this.handleWheelEvent);

    this.closeQRCodeModal(); // 确保在组件销毁前关闭模态框并清除定时器
  },
  methods: {
    loadLogin() {
      if (!this.userInfo) {
        this.$message.info('请先登录');
        this.showQRCode()
      }
    },
    /** 提交按钮 */
    submitForm() {
      if (this.userInfo) {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            this.$request.post('/apis/user/feedback', {
              code: this.form.code,
              description: this.form.description,
              email: this.form.email,
              img: this.form.img,
              title: this.form.title,
              uuid: this.uuid,
            }).then(res => {
              this.$message.success('反馈成功，静等回复~')
              this.form = ''
              this.fileList = []
              this.$router.push('/front/success')
            })
          }
        })
      } else {
        this.$message.info('请先登录');
        this.showQRCode()
      }
    },
    showQRCode() {
      this.showQRCodeModal = true; // 显示模态框
      this.fetchQRCode(); // 请求二维码数据

      // 设置每60秒刷新二维码的定时器
      this.refreshInterval = setInterval(() => {
        this.fetchQRCode(); // 重新获取二维码
      }, 60000); // 60秒

      // 设置每2秒检查扫码状态的定时器
      this.checkStatusInterval = setInterval(() => {
        if (this.data.ticket) {
          this.checkScanStatus(this.data.ticket);
        }
      }, 2000);
    },
    closeQRCodeModal() {
      this.showQRCodeModal = false; // 关闭模态框
      // this.$router.push('/front/homeFront')
      // 清除所有定时器
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval);
        this.refreshInterval = null;
      }
      if (this.checkStatusInterval) {
        clearInterval(this.checkStatusInterval);
        this.checkStatusInterval = null;
      }
    },
    close() {
      this.closeQRCodeModal()
      this.$router.push('/front/homeFront')
    },
    fetchQRCode() {
      return this.$request.get('/wx/getQR').then(res => {
        this.data = res.data
      })
    },
    checkScanStatus() {
      return this.$request.get(`/wx/login/status?ticket=${this.data.ticket}`).then(res => {
        if (res.msg === 'failed') {
          // 扫码失败或未关注
          // this.$message.error('扫码失败或未关注公众号，请重新尝试！');
        } else {
          // 关闭模态框
          this.closeQRCodeModal()
          // 显示登录成功提示
          this.$message.success('登录成功！')
          // this.token = response.data.msg
          // const token = response.data.msg; // 或者可能是 response.data.msg，但通常 msg 是状态信息，不是 token
          // 将 token 存储到 localStorage
          localStorage.setItem("token", (res.msg))
          this.loadUserInfo()
        }
      })
    },
    loadUserInfo() {
      const token = this.getToken();
      return this.$request.get('/apis/user/info', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }).then(res => {
        localStorage.setItem("userInfo", JSON.stringify(res))  // 存储用户数据
        window.location.reload()
      })
      // } else if (res.status === 401) { // 检查是否因为token过期而返回401状态码
      //   this.$message.error('Token expired, please log in again.');
      //   this.showQRCode(); // 显示二维码或其他登录方式
    },
    getToken() {
      return localStorage.getItem('token');
    },
    loadcaptchaImage() {
      return this.$request.get('/captchaImage').then(res => {
        this.Image = res.img
        this.uuid = res.uuid
      })
    },
    updataImg() {
      this.loadcaptchaImage()
    },
    handleWheelEvent(event) {
      // 检查是否按下了Ctrl键
      if (event.ctrlKey) {
        // 防止页面的默认缩放行为
        //event.preventDefault();

        // 判断滚轮方向
        if (event.deltaY < 0) {
          // 滚轮向上滚动，放大页面
          this.scale = Math.min(this.scale + 0.1, 2);  // 最大放大到2倍
        } else {
          // 滚轮向下滚动，缩小页面
          this.scale = Math.max(this.scale - 0.1, 0.5);  // 最小缩小到0.5倍
        }
      }
    },
    handleImgSuccess(response, file, fileList) {
      if (response.code == '200') {
        this.$message.success('上传成功')
        this.form.img = response.url
      } else {
        this.$message.error(response.msg)  // 弹出错误的信息
        this.fileList = []
      }
    },
    toContact() {
      this.$router.push({
        name: 'Contact',
        query: {
          activeIndex: 1
        }
      })
      this.showQRCodeModal = false
    },
    toPrivate() {
      this.$router.push({
        name: 'Contact',
        query: {
          activeIndex: 3
        }
      })
      this.showQRCodeModal = false
    },
  },
}
</script>

<style scoped>
/deep/ .el-input__inner {
  height: 66px;
}

/deep/ .el-form-item__label {
  font-size: 16px;
}

.captcha-container {
  display: inline-block;
  position: relative;
}

.captcha-image {
  height: 66px;
  border-radius: 8px;
  border: 1px solid #2A60C9;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 轻微的阴影效果，提升立体感 */
  object-fit: cover;
  margin-left: 8px;
  transition: transform 0.2s ease; /* 简单的过渡效果，用于鼠标悬停等交互 */
}

.captcha-image:hover {
  transform: scale(1.05); /* 稍微放大图片 */
}

.container {
  width: 1200px; /* 设置最大宽度 */
  margin: 0 auto; /* 居中显示 */
}

.custom-breadcrumb {
  padding: 26px 0 20px 0;
  margin-left: 20px;
}

.label {
  color: #409EFF;
  font-size: 12px;
  margin-left: 8px;
}

.img {
  width: 100%;
  height: 330px;
  border-radius: 36px;
  padding: 10px 20px
}

.feed {
  text-align: center;
  display: flex;
  flex-direction: column;
  margin-top: 30px
}

.back {
  font-size: 27px;
  color: blue;
  font-weight: bold;
  margin-bottom: 8px
}

.feedBack {
  font-size: 16px;
  margin-bottom: 18px
}

.form {
  margin: 10px 36px;
  padding: 15px 13px;
  background-color: #fff;
}

.upload {
  display: flex;
  flex-direction: row
}

.input {
  font-size: 16px;
}

.input-img {
  font-size: 16px;
  width: 80%;
}

.qrcode-login {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  flex-direction: column;
}

.qrcode-modal {
  margin: 60px 10px 0 0;
  text-align: center;
  align-items: center;
}

.qrcode-img {
  border: 1px solid #e0e0e0;
  text-align: center;
  width: 200px;
  height: 200px;
  padding: 5px;
}

.close-btn {
  position: absolute; /* 绝对定位 */
  top: 10px; /* 距离顶部10px */
  right: 16px; /* 距离右边10px */
  z-index: 1001; /* 确保关闭按钮在模态框内容的上方 */
  border: none;
  font-size: 25px;
  color: black;
}

.overlays {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 灰色背景，透明度 50% */
  z-index: 1000;
}
</style>